﻿using System.Windows;
using System.Windows.Controls;

namespace SqlConvertTool;

public class PasswordHelper
{
    public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached(
        "Password", typeof(string), typeof(PasswordHelper), new PropertyMetadata(string.Empty, OnPasswordPropertyChanged));

    private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if(d is PasswordBox passwordBox)
        {
            passwordBox.PasswordChanged -= PasswordChanged;
            if (!GetIsUpdating(passwordBox))
            {
                passwordBox.Password = e.NewValue.ToString();
            }
            passwordBox.PasswordChanged += PasswordChanged;
        }       
    }

    public static void SetPassword(DependencyObject element, string value)
    {
        element.SetValue(PasswordProperty, value);
    }

    public static string GetPassword(DependencyObject element)
    {
        return (string)element.GetValue(PasswordProperty);
    }

    public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached(
        "Attach", typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));

    private static void Attach(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not PasswordBox passwordBox)
        {
            return;
        }

        if ((bool)e.OldValue)
        {
            passwordBox.PasswordChanged -= PasswordChanged;
        }

        if ((bool)e.NewValue)
        {
            passwordBox.PasswordChanged += PasswordChanged;
        }
    }

    private static void PasswordChanged(object sender, RoutedEventArgs e)
    {
        if (sender is PasswordBox passwordBox)
        {
            SetIsUpdating(passwordBox, true);
            SetPassword(passwordBox, passwordBox.Password);
            SetIsUpdating(passwordBox, false);
        }      
    }

    public static void SetAttach(DependencyObject element, bool value)
    {
        element.SetValue(AttachProperty, value);
    }

    public static bool GetAttach(DependencyObject element)
    {
        return (bool)element.GetValue(AttachProperty);
    }

    public static readonly DependencyProperty IsUpdatingProperty = DependencyProperty.RegisterAttached(
        "IsUpdating", typeof(bool), typeof(PasswordHelper), new PropertyMetadata(default(bool)));

    public static void SetIsUpdating(DependencyObject element, bool value)
    {
        element.SetValue(IsUpdatingProperty, value);
    }

    public static bool GetIsUpdating(DependencyObject element)
    {
        return (bool)element.GetValue(IsUpdatingProperty);
    }
}
